interface DragOptions {
  onDown(e: TouchEvent | MouseEvent): void | boolean
  onStart(e: TouchEvent | MouseEvent): void
  onMove(e: TouchEvent | MouseEvent): void
  onEnd(): void
}

export default function useDarg({ onDown, onStart, onMove, onEnd }: DragOptions) {
  let isStart = false
  return {
    touchstart(e: TouchEvent) {
      if (onDown(e) === false) {
        isStart = false
        return
      }
      isStart = true
      onStart(e)
    },
    touchmove(e) {
      if (isStart === false) return
      onMove(e)
    },
    touchend(e) {
      if (isStart === false) return
      const touches = e.touches
      if (touches.length === 0) {
        onEnd()
      } else {
        onStart(e)
      }
    },
    touchcancel() {
      onEnd()
    },
  }
}
